package com.ohuang.download;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.ohuang.download.util.FileUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

public class DownLoadManager {
    public static final String TAG="DownLoadManager";
    private  OhDownLoad ohDownLoad;


   private RemoteFile2File remoteFile2File=new MD5Name(this);
    private  String path="";

    public DownLoadManager(String path,OhDownLoad ohDownLoad) {
        this.path=path;
        this.ohDownLoad=ohDownLoad;
    }
    public DownLoadManager(String path,OhDownLoad ohDownLoad,ReName reName) {
        this.path=path;
        this.ohDownLoad=ohDownLoad;
        if (reName!=null){
            remoteFile2File=new RemoteFile2File() {
                @Override
                public File remote2File(RemoteFile remoteFile) {
                    return new File(path+"/"+reName.reName(remoteFile));
                }
            };
        }
    }



    public  OhDownLoad get() {
        return ohDownLoad;
    }

    /**
     * 下载文件   若当前url正在下载,不会自动调用SimpleDownLoadTask.download方法
     *
     * @param url
     * @param simpleDownLoadListener
     * @return
     */
    public  SimpleDownLoadTask download(String url, SimpleDownLoadListener simpleDownLoadListener) {

        SimpleDownLoadTask simpleDownLoadTask = new SimpleDownLoadTask(get(), url, simpleDownLoadListener, new Handler(Looper.getMainLooper()),remoteFile2File );
        if (isDownload(url)){//若当前url正在下载  直接return  不自动调用download方法
            return simpleDownLoadTask;
        }
        simpleDownLoadTask.download();

        return simpleDownLoadTask;

    }

    /**
     * 清理所有下载的文件  注意不要在下载和使用的文件的时候清理
     */
    public  void clearFile(){
        File file = new File(path);
        if (file.exists()){
            FileUtil.delete(file);
        }
    }

    /**
     * 当前url是否在下载
     * @param url
     * @return
     */
    public  boolean isDownload(String url) {
        List<AbstractDownloadTask> runningTask = get().getRunningTask();
        List<AbstractDownloadTask> waitingTask = get().getWaitingTask();
        List<PreDownLoadTask> runningPreTask = get().getRunningPreTask();
        List<PreDownLoadTask> waitingPreTask = get().getWaitingPreTask();
        for (AbstractDownloadTask abstractDownloadTask : runningTask) {
            if (abstractDownloadTask.getUrl().equals(url)) {
                return true;
            }
        }
        for (AbstractDownloadTask abstractDownloadTask : waitingTask) {
            if (abstractDownloadTask.getUrl().equals(url)) {
                return true;
            }
        }
        for (PreDownLoadTask abstractDownloadTask : runningPreTask) {
            if (abstractDownloadTask.getUrl().equals(url)) {
                return true;
            }
        }
        for (PreDownLoadTask abstractDownloadTask : waitingPreTask) {
            if (abstractDownloadTask.getUrl().equals(url)) {
                return true;
            }
        }

        return false;
    }

    public interface ReName{

       String reName(RemoteFile remoteFile);
    }


    private static class MD5Name  implements RemoteFile2File {
        public DownLoadManager downLoadManager;

        public MD5Name(DownLoadManager downLoadManager) {
            this.downLoadManager = downLoadManager;
        }

        public  String getMD5Str(String str) {
            byte[] digest = null;
            try {
                MessageDigest md5 = MessageDigest.getInstance("md5");
                digest = md5.digest(str.getBytes("utf-8"));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //16是表示转换为16进制数
            String md5Str = new BigInteger(1, digest).toString(16);
            return md5Str;
        }
        /**
         * 获取文件后缀类型
         *
         * @param urlFilePath
         * @return
         */
        public String getUrlFileSuffixType(String urlFilePath) {
            try {
                return urlFilePath.substring((urlFilePath.lastIndexOf('.')));
            }catch (Exception exception){

            }
            return "";
        }

        /**
         * @param urlFilePath
         * @return
         */
        public String getUrlFileName(String urlFilePath) {
            String[] split = urlFilePath.split("\\/");
            return split[split.length - 1];
        }


        @Override
        public File remote2File(RemoteFile remoteFile) {
            if (!TextUtils.isEmpty(remoteFile.fileName)) {
                String urlFileSuffixType = getUrlFileSuffixType(remoteFile.fileName);
                String md5Str = getMD5Str(remoteFile.url);
                String fileName = md5Str;
                if (!TextUtils.isEmpty(urlFileSuffixType)) {
                    fileName = md5Str + urlFileSuffixType;
                }
                return new File(downLoadManager.path+ "/" + fileName);
            } else {

                String urlFileSuffixType = getUrlFileSuffixType(remoteFile.url);
                if (urlFileSuffixType.length() > 8) {
                    String[] split = remoteFile.contentType.split("/");
                    String s = split[split.length - 1];
                    String fileName = null;

                    if (!TextUtils.isEmpty(s)) {
                        String md5Str = getMD5Str(remoteFile.url);
                        fileName = md5Str + "." + s;
                    }
                    if (fileName != null) {
                        return new File(downLoadManager.path + "/" + fileName);
                    }
                } else {
                    String md5Str = getMD5Str(remoteFile.url);
                    String fileName = md5Str;
                    if (!TextUtils.isEmpty(urlFileSuffixType)) {
                        fileName = md5Str + urlFileSuffixType;
                    }
                    return new File(downLoadManager.path + "/" + fileName);
                }

            }
            return null;
        }
    }

}
